
<script lang="ts">
import axios from 'axios';
import router from "../../router";
import {User, Lock} from '@element-plus/icons-vue'
import { ref } from 'vue';


export default {
  setup: function () {


    const role = ref('CUSTOMER');  // 用户身份选择（消费者、商家、管理员）
    const username = ref('');
    const password = ref('');
    const confirmPassword = ref('');
    const errorMessage = ref('');
    const successMessage = ref('');

    // 注册方法
    const register = async () => {
      // 输入验证
      if (password.value !== confirmPassword.value) {
        errorMessage.value = '密码和确认密码不一致';
        return;
      }

      const registrationData = new URLSearchParams();
      registrationData.append('username', username.value);
      registrationData.append('password', password.value);
      registrationData.append('role', role.value);

      try {
        // 调用后端注册接口
        const response = await axios.post('/api/register', registrationData, {
          headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        });

        if (response.data.success) {
          // 根据用户选择的角色，发送不同的登录请求
          const loginData = {
            username: username.value,
            password: password.value,
          };

          // 根据角色决定登录接口
          let loginUrl = '';
          if (role.value === 'customer') {
            loginUrl = '/api/login/customer';
          } else if (role.value === 'seller') {
            loginUrl = '/api/login/seller';
          } else if (role.value === 'admin') {
            loginUrl = '/api/login/admin';
          }

          const loginResponse = await axios.post(loginUrl, loginData);

          if (loginResponse.data.success) {
            // 将用户信息存储到 localStorage 或 sessionStorage
            localStorage.setItem('user', JSON.stringify(loginResponse.data.user));

            await router.push({name: 'Products'});
          } else {
            errorMessage.value = '自动登录失败，请稍后重试';
          }
        } else {
          errorMessage.value = '注册失败，请稍后重试';
        }
      } catch (error) {
        errorMessage.value = '请求失败，请检查网络连接';
        console.error(error);
      }
    };
    const navigateToLogin = () => {
      router.push({name: "Login"});
    }
    return {
      role,
      username,
      password,
      confirmPassword,
      errorMessage,
      successMessage,
      register,
      User,
      Lock,
      navigateToLogin
    };
  },
};
</script>
<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">

    <!-- 注册表单 -->
    <el-form ref="form" size="large" autocomplete="off">
      <el-form-item>
        <h1>注册</h1>
      </el-form-item>
      <el-form-item prop="role">
        <el-select v-model="role" placeholder="请选择角色">
          <el-option label="消费者" value="CUSTOMER"  />
          <el-option label="商家" value="SELLER"/>
          <el-option label="管理员" value="ADMIN" />
        </el-select>
      </el-form-item>
      <el-form-item prop="username">
        <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="username"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码"
                  v-model="confirmPassword"></el-input>
      </el-form-item>
      <el-form-item prop="rePassword">
        <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码"
                  v-model="confirmPassword"></el-input>
      </el-form-item>
      <!-- 注册按钮 -->
      <el-form-item>
        <el-button class="button" type="primary" auto-insert-space @click="register()">注册</el-button>
      </el-form-item>
      <el-form-item class="flex">
        <el-link type="info" :underline="false" @click="navigateToLogin()">
          ← 返回
        </el-link>
      </el-form-item>
    </el-form>
    </el-col>
  </el-row>

</template>

